package com.example.obs.config;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.obs.dao.UserMapper;
import com.example.obs.model.domin.User;
import com.example.obs.service.UserService.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * EasyExcel读取用户数据监听器
 * @author Kevin
 * @date 2020-09-18 14:59
 */
@Slf4j
@Component
public class UserDataListener extends AnalysisEventListener<User> {

    private final UserService userService;
    private final UserMapper userMapper;

    private final ObjectMapper objectMapper;

    private Map<String, User> map = new HashMap<>();

    private static final String PASSWORD = "e10adc3949ba59abbe56e057f20f883e";

    public UserDataListener(UserMapper userMapper, ObjectMapper objectMapper,UserService userService) {
        this.userService=userService;
        this.userMapper = userMapper;
        this.objectMapper = objectMapper;
    }


    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        // 初始密码为123456
        user.setPassword(PASSWORD);
        map.put(user.getUserId(), user);
        try {
            log.info("[批量导入用户]解析到一条数据：{}", objectMapper.writeValueAsString(user));
        } catch (JsonProcessingException e) {}
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 解析完毕，记录入库
        Collection<User> users = map.values();
        int count1 = userService.addUserFolders(users);
        int count = userMapper.addAllUser(users);
        log.info("[批量导入用户]导入完毕，总计：{}条", count);
        log.info("[批量创建用户文件夹]创建完毕，总计：{}条", count1);
        map.clear();
    }

}
